<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="登录账号">
              <a-input v-model="queryParam.loginName" placeholder=""/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="用户角色">
              <a-select v-model="queryParam.roleId" placeholder="请选择">
                <a-select-option v-for="role in roles" :key="role.id">{{ role.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="8" :sm="24">
              <a-form-item label="用户姓名">
                <a-input v-model="queryParam.userName" placeholder=""/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="数据权限">
                <a-tree-select
                  v-model="queryParam.unitId"
                  v-decorator="['unitId', {rules: [{required: true, message: '请选择部别'}]}]"
                  style="width: 100%"
                  :tree-data="treeData"
                  :dropdown-style="{ maxHeight: '300px', overflow: 'auto' }"
                  placeholder="请选择"
                  allow-clear
                  :treeDefaultExpandedKeys="expandedKeys"
                />
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="!advanced && 8 || 24" :sm="24">
            <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
              <a @click="toggleAdvanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="$refs.addUser.add()">新建</a-button>
<!--      <a-button type="dashed" @click="tableOption">{{ optionAlertShow && '关闭' || '开启' }}提示</a-button>-->
      <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="remove">
            <remove-user ref="removeUser" :userIds="selectedRowKeys.join(',')" @ok="handleOk"/>
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作 <a-icon type="down" />
        </a-button>
      </a-dropdown>
      <a-dropdown  v-action:edit v-else-if="selectedRowKeys.length == 0">
        <a-button style="margin-left: 8px">
          批量操作 <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <s-table
      ref="table"
      size="default"
      rowKey="key"
      :columns="columns"
      :data="loadData"
      :alert="options.alert"
      :rowSelection="options.rowSelection"
      showPagination="auto"
    >
      <span slot="roleId" slot-scope="text">
        <a-tag color="#108ee9">{{ text | roleTextFilter }}</a-tag>
      </span>
      <span slot="unitId" slot-scope="text">
        <a-tag color="cyan">{{ text | unitTextFilter }}</a-tag>
      </span>
      <span slot="userType" slot-scope="text">
        <a-tooltip placement="topLeft">
          <a-tag :color="text | statusColorFilter">{{ text | statusTextFilter }}</a-tag>
        </a-tooltip>
      </span>
      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleResetPwd(record)">密码</a>
          <a-divider type="vertical" v-if="record.userType === 1"/>
<!--          <remove-user ref="removeUser" :userIds="String(record.userId)" @ok="handleOk"/>-->
<!--          <a-divider type="vertical" />-->
          <update-user-type ref="updateUserType" :userId="record.userId" @ok="handleOk" v-if="record.userType === 1"/>
        </template>
      </span>
    </s-table>
    <add-user ref="addUser" :roles="roles" :units="units" @ok="handleOk" />
    <edit-user ref="editUser" :roles="roles" :units="units" @ok="handleOk"/>
    <reset-pwd-user ref="resetPwdUser" @ok="handleOk"/>
  </a-card>
</template>

<script>
// import moment from 'moment'
import { STable } from '@/components'
import { queryUser } from '@/api/basic/user'
import { listRole } from '@/api/system/role'
import { listUnit, listUnitTree } from '@/api/basic/unit'
import AddUser from './modules/user/AddUser'
import EditUser from './modules/user/EditUser'
import RemoveUser from './modules/user/RemoveUser'
import UpdateUserType from './modules/user/UpdateUserType'
import ResetPwdUser from './modules/user/ResetPwdUser'
import { TreeSelect } from 'ant-design-vue'

// 用于处理过滤器动态获取数据
let that
const UserType = {
  0: {
    text: '停用',
    color: 'red'
  },
  1: {
    text: '正常',
    color: 'green'
  }
}

export default {
  name: 'UserList',
  components: {
    STable,
    AddUser,
    EditUser,
    RemoveUser,
    UpdateUserType,
    ResetPwdUser,
    ATreeSelect: TreeSelect
  },
  data () {
    return {
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 角色对象
      roles: [],
      units: [],
      expandedKeys: [1],
      treeData: [],
      // 表头
      columns: [
        {
          title: '登录账号',
          dataIndex: 'loginName',
          align: 'center'
        },
        {
          title: '用户姓名',
          dataIndex: 'userName',
          align: 'center'
        },
        {
          title: '部别',
          dataIndex: 'unitName',
          scopedSlots: { customRender: 'unitName' },
          align: 'center'
        },
        {
          title: '角色',
          dataIndex: 'roleId',
          scopedSlots: { customRender: 'roleId' },
          align: 'center'
        },
        {
          title: '数据权限',
          dataIndex: 'unitId',
          scopedSlots: { customRender: 'unitId' },
          align: 'center'
        },
        {
          title: '状态',
          dataIndex: 'userType',
          scopedSlots: { customRender: 'userType' },
          align: 'center'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        // 统一处理查询参数，便于后端表格DTO用固定参数接收
        const queryJson = { 'queryParam': JSON.stringify(this.queryParam) }
        return queryUser(Object.assign(parameter, queryJson))
          .then(res => {
            return res.result
          })
      },
      selectedRowKeys: [],
      selectedRows: [],

      // custom table alert & rowSelection
      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: true
    }
  },
  filters: {
    roleTextFilter (roleId) {
      let roleName = ''
      for (const role of that.roles) {
        if (parseInt(role.id) === parseInt(roleId)) {
          roleName = role.name
          break
        }
      }
      return roleName
    },
    statusTextFilter (userType) {
      return UserType[userType].text
    },
    statusColorFilter (userType) {
      return UserType[userType].color
    },
    unitTextFilter (unitId) {
      let unitIdName = ''
      for (const unit of that.units) {
        if (parseInt(unit.unitId) === parseInt(unitId)) {
          unitIdName = unit.unitName
          break
        }
      }
      return unitIdName
    }
  },
  beforeCreate () {
    that = this
  },
  created () {
    // this.tableOption()
    listRole()
      .then(res => {
        if (res.message !== 'error') {
          this.roles = res.result
        } else {
          this.$message.error('操作失败！')
        }
      })
    listUnit()
      .then(res => {
        if (res.message !== 'error') {
          this.units = res.result
        } else {
          this.$message.error('操作失败！')
        }
      })
    listUnitTree()
      .then(res => {
        if (res.message !== 'error') {
          this.treeData = res.result
        } else {
          this.$message.error('操作失败！')
        }
      })
  },
  methods: {
    // tableOption () {
    //   if (!this.optionAlertShow) {
    //     this.options = {
    //       alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
    //       rowSelection: {
    //         selectedRowKeys: this.selectedRowKeys,
    //         onChange: this.onSelectChange
    //       }
    //     }
    //     this.optionAlertShow = true
    //   } else {
    //     this.options = {
    //       alert: false,
    //       rowSelection: null
    //     }
    //     this.optionAlertShow = false
    //   }
    // },
    handleEdit (record) {
      this.$refs.editUser.edit(record)
    },
    handleResetPwd (record) {
      this.$refs.resetPwdUser.resetPwd(record.userId)
    },
    handleOk () {
      this.$refs.table.clearSelected()
      this.$refs.table.refresh(false)
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    }
  }
}
</script>
